$(function() {
	//失去焦点判读是否为空
	$("._blur_param").blur(function() {
		var that = $(this);
		var id = that.attr('id');
		if(value != '' && !checkEnName(value)) {
			add_param_error(id);
			return;
		}
	});

	//提交审核
	$("._api_add_submit").click(function() {
		var data = getApiData();
		data.api_charge_rules = getPackageData();
		if($('.warning').length > 0){
			//offsetTop兼容性解决
			function offsetTop( elements ){
				var top = elements.offsetTop;
				var parent = elements.offsetParent;
				while( parent !== null ){
					top += parent.offsetTop;
					parent = parent.offsetParent;
				}
				return top;
			};
			//本页跳转
			$('#tab1').scrollTop(offsetTop($('.warning')[0])-160)
			return;
		}
		if(!data) {
			return;
		}
		var cur = $(this);
		// 按钮置为不可点击
		it_enable(cur, true);
		$('#register').attr("disabled", true);
		$('#register_api').text('');
		run_waitMe('register');
		function run_waitMe(register) {
			$('#register_api').waitMe({
				effect: 'ios',
				bg: 'rgba(16,128,242,0)',
				text: '提交中...',
				color: '#fff',
				padding: '10px',
				sizeW: '',
				sizeH: '',
				source: 'img.svg'
			});
		}
		data.api_auth_status = 1; //待审
		data.api_status = 0;
		
		$.ajax({
			url: '/apiworks/apiAdd.html',
			type: 'POST',
			dataType: 'json',
			async: true,
			data: data,
			success: function(req) {
				it_enable(cur, false);
				$('#register').attr("disabled", false);
				$('#register_api').waitMe('hide');
				$('#register_api').text('提交审核');
				if(req.status == 200) {
					$("._api_id").val(req.data);
					$("#continueBox").fadeIn("slow");
					$("._confirm_btn").unbind('click').click(function() {
						$("#delBox").fadeOut("fast");
						location.href = "/apiworks/apiAdd.html?service_id=" + $('._service_id').val();
					});
					$("._close_btn").unbind('click').click(function() {
						$("#delBox").fadeOut("fast");
						location.href = "/apiworks/apiList.html?service_id=" + $('._service_id').val() + "&api_type=1";
					});				
				} else {
					if(req.status == 1) {
						add_auth_error(req.data, req.msg);
					} else {
						show_msg({
							msg: req.msg,
							type: 'error'
						});
					}
				}
				return false;
			},
			error: function() {
				it_enable(cur, false);
				$('#register').attr("disabled", false);
				$('#register_api').waitMe('hide');
				$('#register_api').text('提交审核');
				show_msg({
					msg: "系统异常",
					type: 'error',
					time: 1500
				});
			}
		});
	});

	//判断API接口地址有效性
	$('._api_uri_').blur(function() {
		var api_request_method = $("input[name='api_request_method']:checked").val();
		var method = 'GET';
		if(api_request_method == 1) {
			method = 'POST';
		}
		var api_url = "http://{$info.service_host}/" + $('._api_uri').val();
		$.ajax({
			url: api_url,
			type: method,
			dataType: 'json',
			async: true,
			success: function(req) {
				if(req.status == 200) {
					//show_msg({msg:req.msg,type:'ok',time:3000});
				} else {
					show_msg({
						msg: 'API地址无效',
						type: 'error',
						time: 1500
					});
				}
				return false;
			},
			error: function() {
				show_msg({
					msg: 'API地址无效',
					type: 'error',
					time: 1500
				});
			}
		});

	});

	//临时保存--这个是保存按钮的
	$('._api_save').click(function() {
		var data = getApiData();
		if(!data) {
			return;
		}

		var cur = $(this);
		// 按钮置为不可点击
		it_enable(cur, true);
		$('#register').text('');
		$('#register_api').attr("disabled", "true");
		run_waitMe('register');
		function run_waitMe(register) {
			$('#register').waitMe({
				effect: 'ios',
				bg: 'rgba(16,128,242,0)',
				text: '保存中...',
				color: '#fff',
				padding: '10px',
				sizeW: '',
				sizeH: '',
				source: 'img.svg'
			});
		}
		data.api_auth_status = 0; //未发布状态
		data.api_status = 0; //草稿
		$.ajax({
			url: '/apiworks/apiAdd.html',
			type: 'POST',
			dataType: 'json',
			async: true,
			data: data,
			success: function(req) {
				$('#register_api').attr("disabled", false);
				$('#register').waitMe('hide');
				$('#register').text('保存');
				if(req.status == 200) {
					show_msg({
						msg: req.msg,
						type: 'ok',
						time: 1000
					});
					$("._api_id").val(req.data);
				} else {
					if(req.status == 1) {
						add_auth_error(req.data, req.msg);
					} else {
						show_msg({
							msg: req.msg,
							type: 'error'
						});
					}
					return;
				}
				return false;
			},
			error: function() {
				$('#register_api').attr("disabled", false);
				$('#register').waitMe('hide');
				$('#register').text('保存');
				show_msg({
					msg: '系统异常，请稍后重试',
					type: 'error',
					time: 1000
				});
			}
		});
	});

	//on new user
	$('#save').click(function() {
		//defining new user
		var user = Object();
		user['name'] = $('#name').val();
		user['email'] = $('#email').val();
		//appening to jput variable
		jPut.users.append(user);
	});
	jPut.users.data = [{
		"name": "Shabeer",
		"email": "user@gmail.com",
		"phone": "+51 23126"
	}];

	//on new user
	$('#save1').click(function() {
		//defining new user
		var user1 = Object();
		user1['name'] = $('#name1').val();
		user1['email'] = $('#email1').val();
		//appening to jput variable
		jPut.users1.append(user1);
	});
	jPut.users1.data = [{
		"name": "Shabeer",
		"email": "user@gmail.com",
		"phone": "+51 23126"
	}];

	//on new user
	$('#save2').click(function() {
		//defining new user
		var user2 = Object();
		user2['name'] = $('#name2').val();
		user2['email'] = $('#email2').val();
		//appening to jput variable
		jPut.users2.append(user2);
	});
	//		$('#save3').click(function() {
	//		//defining new user
	//		var user2 = Object();
	//		user2['name'] = $('#name2').val();
	//		user2['email'] = $('#email2').val();
	//		//appening to jput variable
	//		jPut.users2.append(user2);
	//	});
	jPut.users2.data = [{
		"name": "Shabeer",
		"email": "user@gmail.com",
		"phone": "+51 23126"
	}];

});

//是否继续添加API
function continuAddApi() {

	$("#continueBox").fadeIn("slow");
	var that = $(this);

	$("._confirm_btn").unbind('click').click(function() {
		$("#delBox").fadeOut("fast");
		return true;
	});

	$("._close_btn").unbind('click').click(function() {
		$("#delBox").fadeOut("fast");
		return false;
	});
}

function getApiData() {
	var service_id = $('._service_id').val();
	var service_name_en = $('._service_name_en').val();
	var service_name = $('._service_name').val();
	var api_name = $('._api_name').val();
	var api_name_en = $('._api_name_en').val();
	var api_introduction = $('._api_introduction').val();
	//var api_timeout = $('._api_timeout').val();

	//请求方式
	var api_request_method = $("input[name='api_request_method']:checked").val()
	var api_result_format = $("._api_result_format").val();
	var api_authorized_type = $("._api_authorized_type").val();
	var api_uri = $('._api_uri').val();

	var api_request_param = JSON.parse(getApiRequestParam("api_request_param", ['name', 'type', 'mast', 'default_value', 'desc'], 5));
	var param_str = getParam(api_request_param);
	var api_sample_url = "http://{$info.service_host}/" + api_uri + "?" + param_str;

	var api_result_field = JSON.parse(getApiRequestParam("api_result_field", ['name', 'type', 'desc'], 3));
	var result_field_str = getResultField(api_result_field);

	var api_error_codes = JSON.parse(getApiRequestParam("api_error_codes", ['code', 'info', 'desc'], 3));
	var api_result_sample = $("._api_result_sample").val();
	var api_other_platform_sample = $("._api_other_platform_sample").val();
	var api_update_type = $("input[name='api_update_type']:checked").val();
	var api_is_charge = $("input[name='api_is_charge']:checked").val();

	//参数为空判断
	batchVer('_blur_rz');

	//有错误样式不允许提交
	if(haserror('_blur_rz')) {
		return false;
	}
	//请求参数判断
	if(param_str == 'no') {
		return false;
	}
	//请求参数判断
	if(result_field_str == 'no') {
		return false;
	}

	// 验证 套餐
	if($('._chargeType input')[1].checked && addJudge() == -1) {
		return false;
	}
		
	//api提交
	var data = {};
	data.service_id = service_id;
	data.api_id = $('._api_id').val();
	data.api_name = api_name;
	data.service_name_en = service_name_en;
	data.service_name = service_name;
	data.api_name_en = api_name_en;
	data.api_introduction = api_introduction;
	//data.api_timeout = api_timeout;
	data.api_request_method = api_request_method;
	data.api_result_format = api_result_format;
	data.api_authorized_type = api_authorized_type;
	data.api_uri = api_uri;
	data.api_sample_url = api_sample_url;
	data.api_request_param = api_request_param;
	data.api_result_field = api_result_field;
	data.api_error_codes = api_error_codes;
	data.api_result_sample = api_result_sample;
	data.api_other_platform_sample = api_other_platform_sample;
	data.api_update_type = api_update_type;
	data.api_is_charge = api_is_charge;

	return data;

}

//拼装请求样例
function getParam(datajson) {

	var param_string = "";
	var rsv = true;
	for(var k in datajson) {
		if(!stringIsNull($.trim(datajson[k].name)) && !checkEnName(datajson[k].name)) {
			rsv = false;
		}
		param_string += "&" + datajson[k].name + "=" + datajson[k].default_value;
	}
	if(!rsv) {
		return 'no';
	}
	param_string = param_string.substr(1);
	param_string = param_string.replace(' ', '');
	return param_string;
}

function getResultField(datajson) {
	var rsv = true;
	for(var k in datajson) {
		if(!stringIsNull($.trim(datajson[k].name)) && !checkEnName(datajson[k].name)) {
			rsv = false;
			//return false;
		}
	}
	if(!rsv) {
		return 'no';
	}
	return 'yes';
}

//获取二维数组值及转json数据格式
function getApiRequestParam(dom_name, params, params_num) {
	var api_request_param = $("input[name^='" + dom_name + "']"); // 获取input标签且name名为 [dom_name] 的
	//console.log(api_request_param);
	var json_params = new Array(); // 新建array

	var array_num = Math.floor(api_request_param.length / params_num); // 间隔
	for(var j = 0; j < array_num; j++) {
		//json_params[j] = new Array();
		json_params[j] = new Object();
	}

	for(var i = 0; i < api_request_param.length; i++) {
		try {
			var num = i % params_num;
			var key = Math.floor(i / params_num);
			var kkey = params[num];
			json_params[key][kkey] = api_request_param[i].value;
		} catch(e) {
			break;
		}

	}

	return JSON.stringify(json_params);
}

// 获取option值
function selectChange(obj, classname, val) {
	var val = $(obj).val();
	$(obj).next('input[name=\'' + classname + '\']').val(val);
}

function checkValue(obj, classname) {
	var value = $(obj).val(); //.attr('value');
	if(value != '' && !checkEnName(value)) {
		$(obj).addClass('warning');
	}
	// //遍历所有子节点值
	$(classname).each(function() {
		if(this != obj) {
			var thisvalue = $(this).val();
			if(thisvalue == value) {
				$(obj).addClass('warning');
				show_msg({
					type: 'warning',
					msg: '值不能重复'
				});
				return false;
			}
		}
	});
}

function checkErrorCodeValue(obj, classname) {
	var value = $(obj).val(); //.attr('value');
	// //遍历所有子节点值
	$(classname).each(function() {
		if(this != obj) {
			var thisvalue = $(this).val();
			if(thisvalue == value) {
				$(obj).addClass('warning');
				show_msg({
					type: 'warning',
					msg: '值不能重复'
				});
				return false;
			}
		}
	});
}

function rmError(obj) {
	$(obj).removeClass('warning');
}

$(function() {
	$(document)
		.on('click', '._request_param_del', function() {
			var that = $(this);
			that.parent().parent('._raw_request_param').remove();
		})

	.on('click', '._return_param_del', function() {
		var that = $(this);
		that.parent().parent('._raw_return_param').remove();
	})

	.on('click', '._error_param_del', function() {
		var that = $(this);
		that.parent().parent('._raw_error_param').remove();
	})
});